﻿using MQTT.Server.Attributes;
using System.Reflection;

namespace MQTT.Server.Handlers
{


    public class ApplicationMessagRouter
    {
        private readonly Dictionary<string, MethodInfo> topicMethodMap = new Dictionary<string, MethodInfo>();

        public ApplicationMessagRouter(IEnumerable<Type> handlerTypes)
        {
            foreach (var handlerType in handlerTypes)
            {
                var methods = handlerType.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
                foreach (var method in methods)
                {
                    var attribute = method.GetCustomAttribute<TopicAttribute>();
                    if (attribute != null)
                    {
                        topicMethodMap[attribute.Topic] = method;
                    }
                }
            }
        }

        public void RouteMessage(string topic, string message)
        {
            foreach (var kvp in topicMethodMap)
            {
                var template = kvp.Key;
                var method = kvp.Value;

                // Match the template with the topic using your own logic
                // For simplicity, let's assume a straightforward comparison here
                if (topic == template)
                {
                    var placeholders = ExtractPlaceholders(template);

                    var arguments = placeholders.ToArray();
                    var handlerInstance = Activator.CreateInstance(method.DeclaringType);
                    method.Invoke(handlerInstance, new[] { arguments });
                }
            }
        }

        private List<string> ExtractPlaceholders(string template)
        {
            var placeholders = new List<string>();
            // Implement your logic to extract placeholders from the template
            return placeholders;
        }
    }
}
